package event

import (
	"context"
	"ez/apps/erp/auto/mc"
	erp "ez/apps/erp/document"
	"ez/apps/tool/service"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"time"
)

func init() {
	ez.Subscribe(mc.NeedEventBeforeCreate, func(v interface{}, ctx context.Context) {
		md, ok := v.(*erp.Need)
		if ok {
			uid := cc.GetUidFromCtx(ctx)
			md.CreateEmpId = uid
			if md.FormEmpId == 0 {
				md.FormEmpId = uid
				md.FormAt = time.Now()
			}
			if md.Sn == "" {
				md.Sn = service.CreateSnByString(ez.ConfigService.AppId,
					"CGSQ-[YY][MM][DD]-[DMAX[3]]", 1)
			}
		}
	})
	ez.Subscribe(mc.NeedAccessControlEvent, func(v interface{}, ctx context.Context) {
		ac, ok := v.(*erp.NeedAccessControl)
		if ok {
			c := cc.New(ac.Session)
			switch ac.Action {
			case "save", "delete", "destroy", "copy", "update":
				uid := c.GetUserId()
				if uid != 1 && uid != ac.Model.CreateEmpId {
					ac.Access = false
					ac.Message = "您没有权限修改该数据"
				}
			}
		}
	})
}
